package com.netty.web.controller;

import com.netty.email.MailService;
import com.netty.utils.GuavaCacheUtil;
import com.netty.utils.R;
import com.netty.web.vo.RequestEntity;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author zl
 * @version 1.0
 * @date 2021/10/26 9:06
 */
@Api(tags = "发送邮件")
@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private MailService mailService;

    @PostMapping(value = "/send")
    public R send(@Validated @RequestBody RequestEntity.SendEmail sendEmail){
        try{
            String yzm = getSixNums();
            //将验证码存放缓存，缓存时间为10分钟
            GuavaCacheUtil.put(sendEmail.getEmail(),yzm);
            String content =  "您的注册码为【"+yzm+"】，请尽快验证，验证码有效期为10分钟。";
            mailService.sendSimpleTextMailActual(sendEmail.getSubject(),
                    content,
                    new String[]{sendEmail.getEmail()},
                    null,
                    null,
                    null);
            return R.ok();
        }catch (Exception e){
            return R.error("发送邮件失败");
        }
    }

    public String getSixNums(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result += random.nextInt(10);
        }
        System.out.println(result);
        return result;
    }


}
